package tree2str;

public class Solution {
      public class TreeNode {
          int val;
          TreeNode left;
          TreeNode right;

          TreeNode() {
          }

          TreeNode(int val) {
              this.val = val;
          }

          TreeNode(int val, TreeNode left, TreeNode right) {
              this.val = val;
              this.left = left;
              this.right = right;
          }
      }
    public String tree2str(TreeNode root) {
          return dfs(root);
    }
    private String dfs (TreeNode root) {
          if(root.left == null&& root.right == null)return root.val+"";
          String ans = root.val+"";
          if(root.left == null ) {
              // 左子树为空 右子树不为空
              ans+="("+")"+"("+dfs(root.right)+")";
          } else if (root.right == null) {
              // 右子树为空 左子树不为空
              ans+="("+dfs(root.left)+")";
          } else {
              ans+="("+dfs(root.left)+")"+"("+dfs(root.right)+")";
          }
          return ans;
    }
}
